<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuth } from '@/utils/useAuth'

const router = useRouter()
const route = useRoute()

// 使用全局认证状态
const { userInfo, fetchUserInfo, logout, getDisplayName } = useAuth()

const navItems = [
  { key: 'home', label: '首页', route: '/home' },
  { key: 'experts', label: '找专家', route: '/appointment' },
  { key: 'hospitals', label: '找医院', route: '#map' },
  { key: 'knowledge', label: '健康问答', route: '/knowledge' },
  { key: 'audit', label: '病历审核', route: '/medical-record-audit' },
  { key: 'other', label: '更多服务', route: '#' }
]

const activeNav = ref('home')
const lastClickedKey = ref(sessionStorage.getItem('activeNav') || 'home')
const showDropdown = ref(false) // 控制下拉框显示

function syncActiveByRoute() {
  const p = route.path
  if (p.startsWith('/appointment')) activeNav.value = 'experts'
  else if (p === '/home' || p === '/') activeNav.value = 'home'
  else if (p === '/knowledge') activeNav.value = 'knowledge'
  else if (p === '/medical-record-audit') activeNav.value = 'audit'
  else {
    activeNav.value = 'home'
  }
}

onMounted(async () => {
  await fetchUserInfo()
})

// 路由变化时同步高亮，初次也会触发
watch(() => route.path, () => {
  syncActiveByRoute()
}, { immediate: true })

function handleLogin() { router.push('/') }

async function handleNavClick(item) {
  // 处理其他字段的点击事件
  if (item.key === 'other') {
    showDropdown.value = !showDropdown.value
    return
  }

  activeNav.value = item.key
  lastClickedKey.value = item.key
  sessionStorage.setItem('activeNav', item.key)
  if (item.route === '#map') {
    if (route.path !== '/home') {
      await router.push('/home')
      await nextTick()
    }
    const el = document.querySelector('.map-section')
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' })
  } else {
    router.push(item.route)
  }
}

// 处理下拉菜单点击
function handleDropdownClick(option) {
  showDropdown.value = false
  if (option === 'health-record') {
    router.push('/my-appointments')
  } else if (option === 'image-recognition') {
    router.push('/image-recognition')
  } else if (option === 'iterator-demo') {
    router.push('/doctors-iterator')
  } else if (option === 'route-observer') {
    router.push('/route-observer-demo')
  }
}

// 点击其他地方关闭下拉框
function handleClickOutside(event) {
  if (!event.target.closest('.nav-tab.other') && !event.target.closest('.dropdown-menu')) {
    showDropdown.value = false
  }
}

// 添加点击事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

// 移除事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 退出登录
function handleLogout() {
  logout()
  router.replace('/') // 使用replace避免返回到已认证页面
}
</script>

<template>
  <header class="header">
    <div class="header-content">
      <div class="logo"><h1>京东医疗</h1></div>
      <div class="nav-tabs">
        <div v-for="item in navItems" :key="item.key"
             class="nav-tab"
             :class="{ active: activeNav === item.key, other: item.key === 'other' }"
             @click="handleNavClick(item)">
          {{ item.label }}
          <div class="underline" />
        </div>
      </div>
      <div class="user-actions">
        <div v-if="userInfo.isLoggedIn" class="user-info">
          <span>你好，{{ getDisplayName() }}</span>
          <el-button type="text" @click="() => router.push('/my-appointments')">我的预约</el-button>
          <el-button type="text" @click="handleLogout">退出登录</el-button>
        </div>
        <div v-else class="login-actions">
          <el-button type="text" @click="handleLogin">你好，请登录</el-button>
          <el-button type="text">免费注册</el-button>
        </div>
      </div>
    </div>

    <!-- 下拉菜单 -->
    <div v-if="showDropdown" class="dropdown-menu">
      <div class="dropdown-item" @click="handleDropdownClick('health-record')">我的预约</div>
      <div class="dropdown-item" @click="handleDropdownClick('image-recognition')">图片识别</div>
      <div class="dropdown-item" @click="handleDropdownClick('iterator-demo')">迭代器演示</div>
      <div class="dropdown-item" @click="handleDropdownClick('route-observer')">路由观察器</div>
    </div>
  </header>
</template>

<style scoped>
.header {
  background-color: #4CAF50;
  color: #fff;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: relative;
}
.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}
.logo h1 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  white-space: nowrap;
}
.nav-tabs {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 40px;
  flex-wrap: nowrap;
}
.nav-tab {
  position: relative;
  font-size: 16px;
  color: #fff;
  cursor: pointer;
  padding: 4px 8px 10px;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.nav-tab:hover {
  color: #00e0ee;
}
.nav-tab .underline {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0;
  width: 28px;
  height: 3px;
  background: transparent;
  border-radius: 3px;
}
.nav-tab.active {
  color: #00e0ee;
}
.nav-tab.active .underline {
  background: #00e0ee;
}

/* 更多服务按钮特殊样式 */
.nav-tab.other::after {
  content: ' ▼';
  font-size: 12px;
  margin-left: 4px;
  color: rgba(255, 255, 255, 0.8);
}

.nav-tab.other:hover::after {
  color: #00e0ee;
}
.user-actions {
  display: flex;
  gap: 20px;
  flex-shrink: 0;
}
.user-info, .login-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  white-space: nowrap;
}

/* 下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 140px;
  border: 1px solid #e0e0e0;
}
.dropdown-item {
  padding: 12px 16px;
  color: #333;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;
  border-bottom: 1px solid #f0f0f0;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.dropdown-item:hover {
  background-color: #f8f9fa;
  color: #4CAF50;
}


@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 10px 0;
  }
  
  .nav-tabs {
    gap: 20px;
    flex-wrap: wrap;
  }
  
  .nav-tab {
    font-size: 14px;
  }
}
</style>


